<template>
  <div class="warpper">

    <div class="form" @click="isgoprolist = false">
      <el-form ref="ruleForm" :model="formData" size="mini" label-width="160px" style="width:85%">
        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="11">
            <el-form-item label="status" prop="status" style="width: 460px;">
              <template slot-scope="scope">
                <span>{{ formData.status }}</span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11" style="text-align: right;">
            <el-form-item v-if="formData.status !='approved'">
              <template slot-scope="scope">
                <el-button plain type="primary" v-permission="['quotationlists.undate']" @click="godisable(true)"
                  :disabled="isapproved"
                  v-if="formData.status =='pending' || formData.status =='rejection'">{{isdiable?"Edit":"Cancel Edit"}}</el-button>
                <el-button plain type="default" v-permission="['quotationlists.void']" @click="editstatus(id, 'voided')"
                  :disabled="isapproved" v-if="formData.status =='pending' && isdiable">Voided</el-button>
                <el-button plain type="danger" v-permission="['quotationlists.rejection']"
                  @click="editstatus(id, 'rejection')" :disabled="isapproved"
                  v-if="formData.status =='pending' && isdiable">Rejection</el-button>
                <el-button plain type="primary" v-permission="['quotationlists.auditing']"
                  @click="editstatus(id, 'approved')" :disabled="isapproved"
                  v-if="formData.status =='pending' && isdiable">Auditing</el-button>


                <el-button plain type="default" @click="close()"
                  v-if="formData.status =='approved' || formData.status =='voided' || formData.status =='rejection'">Back</el-button>
              </template>
            </el-form-item>
            <el-form-item v-if="formData.status =='approved'">
              <template slot-scope="scope">
                <el-button plain type="default" @click="goinorder()">Sale Order</el-button>
                <el-button plain type="default" @click="prints(3)">Print Quotation</el-button>
                <el-button plain type="default" @click="close()">Back</el-button>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog title="" :visible.sync="caigou3" width="840px" @close="onCloseDialog">

      <div class="layui-fluid layui-anim layui-anim-upbit your-background-class" id="print_body3"
        style="padding: 0; background-image: url(https://v.ttxcx.net/static/img/bjdan.png);width: 840px;background-repeat: no-repeat;height: 1190px;background-size: cover;">
        <div>
          <input v-model="printform.ordernumber" class="ordernumber">
        </div>
        <div style="display: flex;justify-content: space-between;padding-top: 70px;">
          <div class="layui-row layui-col-space15" style="padding-left: 102px;">
            <div class="layui-col-md12">
              <div class="layui-card" style="width: 250px;">
                <div style="width: 100%;text-align: left;">
                  <input v-model="printform.addtime" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size:14px;font-weight: 100;">
                </div>
                <div style="width: 100%;text-align: left;">
                  <input type="textarea" v-model="printform.customername" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size:14px;font-weight: 400;">
                </div>
                <div style="width: 100%;text-align: left;">
                  <input v-model="printform.attention" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                </div>
              </div>
            </div>
          </div>



          <div class="layui-row layui-col-space15" style="padding-right: 10%;">
            <div class="layui-col-md12">
              <div class="layui-card" style="width: 250px;">
                <div style="width: 100%;text-align: left;">
                  <input v-model="printform.fax" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                </div>
                <div style="width: 100%;text-align: left;">
                  <input type="textarea" v-model="printform.tel" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                </div>
                <div style="width: 100%;text-align: left;">
                  <input value="1/1" class="layui-input"
                    style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
                </div>
              </div>
            </div>
          </div>
        </div>


        <div class="layui-row layui-col-space15" style="padding-left: 130px;padding-top: 9px;">
          <div class="layui-col-md12">
            <div class="layui-card" style="width: 500px;">
              <div style="width: 100%;text-align: left;">
                <input v-model="printform.term+' '+printform.termdataday" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
              </div>
              <div style="width: 100%;text-align: left;font-size: 16px;">
                <input type="textarea" v-model="printform.leadtime" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
              </div>
              <div style="width: 100%;text-align: left;font-size: 16px;">
                <input v-model="printform.paymentterm" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
              </div>
              <div style="width: 100%;text-align: left;font-size: 16px;">
                <input v-model="printform.validityday" class="layui-input"
                  style="padding-left: 0;border:0;width: 100%;text-align: left;font-size: 14px;font-weight: 100;">
              </div>
            </div>
          </div>
        </div>



        <div style="display: flex;padding-top: 70px;justify-content: space-between;">

          <div style="padding-left: 50px;width: 800px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 14px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p style="display: inline-block;width: 28px;">{{index+1}} </p>
              <p style="display: inline-block;width: 430px;">{{ item.productname}} / {{ item.sku}}<br>{{ item.note}}</p>
              <p style="display: inline-block;width: 100px;">{{ item.unitweight}}</p>
              <p style="display: inline-block;width: 72px;">{{ item.unitprice}}</p>
              <p style="display: inline-block;width: 100px;">{{ item.minimumorder}}</p>
            </div>
          </div>

          <!--          <div style="padding-right: 5%;width: 100px;">
            <div style="padding-left: 0;border:0;text-align: left;font-size: 16px;width: 500px;"
              v-for="(item, index) in printform.procureditem" :key="index" :item="item">
              <p>{{ item.unitweight}}{{ item.unitprice}}{{ item.minimumorder}}</p>
            </div>
          </div> -->

        </div>
      </div>

      <div class="layui-inline ipt layui-col-md12" id="wdDs"
        style="text-align:right;margin-top:20px;margin-right:60px;display: flex;align-items: center;justify-content: space-between">
        <span class="layui-btn print ipt" id="indfs"><i class="iconfont icon-font-61d" style="color: #fff;"></i></span>
        <el-button type="primary" v-print="'#print_body3'" style="margin-bottom: 10px;">Print</el-button>
      </div>
    </el-dialog>


    <div class="form" id="cadd" @click="isgoprolist = false">
      <el-form ref="ruleForm" :model="formData" :rules="rules" size="mini" label-width="168px" style="width:95%"
        :disabled="isdiable">

        <el-row :gutter="20" v-if="isNew">
          <el-col :span="11">
            <el-form-item label="Quotation Template" style="width: 460px;">
              <el-select @change="changeqt" v-model="qtordernumber" placeholder="Select Quotation" style="width:290px;"
                filterable>
                <el-option v-for="item in quotationdescriptions" :key="item.id" :label="item.ordernumber"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">

          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Order Number" prop="ordernumber" style="width:460px">
              <el-input v-model="formData.ordernumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Create Date" prop="created_at" style="width:460px">
              <el-date-picker v-model="formData.addtime" type="date" style="width:290px;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Customer Name" prop="customer_id" style="width: 460px;">
              <el-select @change="changetermc" v-model="formData.customer_id" placeholder="Select Customer"
                style="width:290px;" filterable remote :remote-method="remoteMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Shipment Term" prop="term" style="width: 480px;">
              <el-select v-model="formData.term" placeholder="Select Shipment" style="width:100px" @change="changeterm">
                <el-option v-for="item in term" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
              <el-input-number v-model="formData.termdata" :min="1" :max="10000" style="width: 100px"></el-input-number>
              <el-select v-model="formData.termdataday" style="width: 85px">
                <el-option v-for="item in shipmenttermday" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>



        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Customer ID" prop="customer_id" style="width: 460px;">
              <el-select @change="changetermc" v-model="formData.customer_id" placeholder="Select Customerid"
                style="width:290px;" filterable remote :remote-method="remoteidMethod">
                <el-option v-for="item in customers" :key="item.id" :label="item.customerid" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="File" prop="certificates" style="width: 460px;">

              <div v-if="isdiable" style="position: relative;">
                <a v-if="formData.certificates" style="font-size: 12px;" :href="formData.certificates"
                  target="_blank"><img src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                </a>
                <i v-else class="el-icon-upload"> upload files </i>
              </div>

              <div v-else style="position: relative;">

                <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="false"
                  :on-change="changeAvatar" :auto-upload="true" :http-request="vgetUploadHandler()" name="file"
                  :limit="1">
                  <img v-if="formData.certificates" src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                  <i v-else class="el-icon-upload"> upload files </i>
                </el-upload>

                <div v-if="formData.certificates">
                  <a style="font-size: 12px;" :href="formData.certificates" target="_blank">view</a>
                  <span style="font-size: 12px;margin-left: 5px; color: red;" @click="vdelcart()">del</span>
                </div>
              </div>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Dedicated sales staff" prop="staff" style="width: 460px;">
              <el-select v-model="formData.staff" placeholder="Select Staff" style="width:290px;">
                <el-option v-for="item in staff" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="11">
            <el-form-item label="Rate" prop="rate" style="width: 460px;">
              <el-input v-model="formData.rate"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Currency" prop="currency" style="width: 460px;">
              <el-select v-model="formData.currency" placeholder="Select Currency" style="width:290px;">
                <el-option v-for="item in currency" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Quotation Validity Day" prop="validityday" style="width: 460px;">
              <el-select v-model="formData.validityday" placeholder="Select validityday" style="width:290px;">
                <el-option v-for="item in validityday" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="11">
            <!--            <el-form-item label="Billing Title" prop="billingtitle" style="width: 460px;">
              <el-input v-model="formData.billingtitle"></el-input>
            </el-form-item> -->
            <el-form-item label="Billing Title" prop="billingtitle" style="width: 460px;">
              <el-select v-model="formData.billingtitle" placeholder="Select Title" filterable style="width:290px"
                @change="changebt">
                <el-option v-for="item in billingtitle" :key="item.id" :label="item.title" :value="item.title">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Fax" prop="fax" style="width: 460px;">
              <el-input v-model="formData.fax"></el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Attention" prop="attention" style="width: 460px;">
              <el-input v-model="formData.attention"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Tel" prop="tel" style="width: 460px;">
              <el-input v-model="formData.tel"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Remarks" prop="remarks" style="width: 460px;">
              <el-input v-model="formData.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">

            <el-form-item label="Quotation Description" prop="quotationdescriptions" style="width: 460px;">
              <el-select v-model="formData.quotationdescriptions" style="width:290px;" multiple>
                <el-option v-for="item in quotationdescriptions" :key="item.id" :label="item.description"
                  :value="item.description">
                </el-option>
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="Quotation Descriptions" prop="quotationdescriptions" style="width: 460px;">
              <el-input v-model="formData.quotationdescriptions"></el-input>
            </el-form-item> -->

          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Payment Term" prop="paymentterm" style="width: 460px;">
              <el-input v-model="formData.paymentterm"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Lead Time" prop="leadtime" style="width: 460px;">
              <el-input v-model="formData.leadtime"></el-input>
            </el-form-item>
          </el-col>
        </el-row>



        <el-form-item class="cadd">

          <el-table ref="multipleTable" :data="formData.procureditem" prop="procureditem"
            :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" border
            @mouseleave.native="handleRowMouseLeave" v-if="formData.procureditem && formData.procureditem.length > 0">
            <el-table-column label="NO" prop="" width="80">
              <template slot-scope="scope">
                <div @mouseenter="handleRowMouseEnter(scope.$index)">
                  <span>{{ scope.$index + 1 }}</span>
                  <img v-if="hoveredIndex==scope.$index" src="../../../assets/jiahao.png"
                    style="width: 20px;height: 20px" @click="oncopyproductname(scope.row, scope.$index)" />
                </div>
              </template>
            </el-table-column>

            <el-table-column label="ProductName" width="150px">
              <template slot-scope="scope">
                <el-input ref="inputRefs" v-model="scope.row.productname"
                  @input="onChangeproductname(scope.row.productname, scope.$index, $event)" :rows="3"
                  type="textarea"></el-input>
              </template>
            </el-table-column>


            <el-table-column label="SKU" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sku" @input="onChangeproductsku(scope.row.sku, scope.$index, $event)"
                  :rows="3" type="textarea"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="Customer SKU">
              <template slot-scope="scope">
                <span>{{scope.row.csku}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Unit Weight /Unit Quantity">
              <template slot-scope="scope">
                <el-input v-model="scope.row.unitweight"></el-input>
              </template>
            </el-table-column>


            <el-table-column label="UOM" width="60px">
              <template slot-scope="scope">
                <span>{{scope.row.uom}}</span>
              </template>
            </el-table-column>

            <el-table-column label="Customer UOM">
              <template slot-scope="scope">
                <span>{{scope.row.cskuom}}</span>
              </template>
            </el-table-column>


            <el-table-column label="Unit Price" width="100px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.unitprice" type="text" oninput="value=value.replace(/[^\d.]/g,'')" />
              </template>
            </el-table-column>

            <el-table-column label="lead time" width="100px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.leadtime" type="text" />
              </template>
            </el-table-column>


            <el-table-column label="Minimum order" width="100px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.minimumorder"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="Description" mini-width="150px">
              <template slot-scope="scope">
                <el-input type="textarea" :rows="3" v-model="scope.row.note"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="Actions" width="110" v-if="isNew || (isEdit && !isdiable)">
              <template slot-scope="scope">
                <el-button plain type="danger" v-permission="['quotationlists.destroy']" @click="removeItem(scope.row)"
                  size="mini">delete</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-left: 170px;" v-if="isNew || (isEdit && !isdiable)">
        <el-button type="primary" @click="addItem" :disabled="isdiable">Add Product</el-button>
        <el-button type="primary" @click="saveHandle('ruleForm')" :disabled="isdiable || isubmit">Submit</el-button>
      </div>
    </div>

    <div class="form plt" v-if="isgoprolist" :style="{ 'top': topx,'left':'600px' }">
      <el-button @click="isgoprolist = false" size="mini"
        style="position: absolute;right: 20px;top: 20px;z-index: 999;height: 40px;color: red;">X</el-button>
      <div class="table">
        <el-table :data="tableData" size="small" stripe border @row-click="handleRowClick" style="width: 100%"
          height="320">
          <el-table-column prop="name" label="Name" width="120" align="center" />
          <el-table-column prop="sku" label="SKU" width="100" align="center" />
          <el-table-column label="Spec" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="Category" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.category.name }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="packaging" label="Packaging" min-width="100" />
          <el-table-column label="Brand" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.brand_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="Price(S$)" width="100" />
          <el-table-column prop="rop" label="ROP Point" width="100" />
          <el-table-column prop="stock" label="Stock Quantity" width="140" />
          <!-- <el-table-column label="Actions" width="200">
            <template slot-scope="scope">
              <el-button plain @click="selectadd(scope.row)">select</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- <div slot="footer" class="dialog-footer" style="margin-left: 50%; margin-top: 10px;">
          <el-button @click="isgoprolist = false" size="mini">close</el-button>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index,
    show,
    update,
    store
  } from "@/api/quotationlist";
  import {
    index as quotationdescriptionsindex
  } from "@/api/quotationtemplate";
  import {
    index as warehouselist
  } from "@/api/warehouse";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    index as skushow
  } from "@/api/suppersku";
  import {
    index as prolist
  } from "@/api/product";
  import {
    index as prowarlist
  } from "@/api/inventory";
  import {
    index as customerindex
  } from "@/api/customer";
  import {
    store as uploadImg
  } from "@/api/medias";
  import {
    index as superindex
  } from "@/api/supplier";
  import {
    index as shipmentermindex
  } from "@/api/shipmenterm";
  import {
    index as billingindex,
  } from "@/api/attention";
  export default {
    name: "stockinadd",
    mixins: [CURD],
    data() {
      return {
        qtordernumber: null,
        shipmenttermday: [{
          id: 1,
          name: "day",
        }, {
          id: 2,
          name: "week",
        }, {
          id: 3,
          name: "month",
        }, {
          id: 4,
          name: "year",
        }],
        billingtitle: [],
        quotationdescriptions: [],
        hoveredIndex: null,
        isubmit: false,
        rowIndex: 0,
        x: 0,
        y: 0,
        topx: '60%',
        isgoprolist: false,
        isdiable: false,
        staff: [{
          id: "KW",
          name: "KW",
        }],
        currency: [{
          id: 1,
          name: "SGD",
        }, {
          id: 2,
          name: "USD",
        }],
        term: [],
        validityday: [{
          id: 14,
          name: 14,
        }, {
          id: 30,
          name: 30,
        }, {
          id: 60,
          name: 60,
        }],
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          termdataday: "day",
          staff: "KW",
          currency: "SGD",
          term: "SOB",
          validityday: 30,
          procureditem: [],
        },
        module: "quotationlist",
        newTitle: "New quotationlist",
        editTitle: "Edit quotationlist",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        suppliers: [],
        warehouse: [],
        xiabiao: -1,
        tindex: 0,
        tableData: [],
        customers: [],
        customersid: [],
        searchForm: {

        },
        printform: {},
        caigou1: false,
        caigou2: false,
        caigou3: false,
        isapproved: false,
        inputElements: [],
        tableDatav: [{
          id: "approved",
          name: "approved",
        }],
      };
    },
    mounted() {

    },
    watch: {
      'formData.procureditem': {
        handler() {
          //this.updateInputElements();
        },
        deep: true
      }
    },
    computed: {
      totalqty() {
        if (this.formData.procureditem) {
          const totalPrice = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
            .qty), 0);
          return totalPrice ? totalPrice : 0
        }
      },
      totalamount() {
        if (this.formData.procureditem) {
          const amount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item.costamount), 0);
          return amount ? amount : 0
        }
      },
    },
    async created() {
      this.id = this.$route.query.id
      if (this.id > 0) {
        this.isEdit = true
        this.isdiable = true
        const {
          data
        } = await show(this.id);
        this.formData = data;
        if (this.formData.status == "approved") {
          this.isapproved = true
        }
        this.formData.quotationdescriptions = this.formData.quotationdescriptions.split(",");
        //this.formData.procureditem = data.formdatalist;
      } else {
        var numStr = "01";
        const {
          data
        } = await index(1, 1);
        var lslist = data;
        if (data.length > 0) {
          var dqskinid = lslist[0].id + 1
          numStr = dqskinid.toString();
        }
        this.isNew = true
        this.isdiable = false
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const day = currentDate.getDate();
        console.log(`${year}-${month}-${day}`);
        this.formData.addtime = `${year}-${month}-${day}`
        this.formData.ordernumber = "QO" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')
        this.addItem()
        this.$nextTick(() => {
          const inputElement = document.querySelector(`.el-table__row input:nth-child(${1})`);
          if (inputElement) {
            if (inputElement) {
              const inputRect = inputElement.getBoundingClientRect();
              this.y = inputRect.left
              this.x = inputRect.top - 30
              console.log('Input coordinates:', this.x, this.y);
            }
          }
        });
      }
      try {
        const {
          data
        } = await customerindex(1, 100);
        this.customers = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }
      try {
        const {
          data
        } = await customerindex(1, 20, {
          cid: 21
        });
        this.customersid = data;
      } catch (error) {
        console.error('Failed to fetch customer:', error);
      }

      try {
        const {
          data
        } = await quotationdescriptionsindex(1, 100);
        this.quotationdescriptions = data;
      } catch (error) {
        console.error('Failed to fetch warehouse:', error);
      }
      try {
        const {
          data
        } = await shipmentermindex(1, 100);
        this.term = data;
      } catch (error) {
        console.error('Failed to fetch term:', error);
      }

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.staff = data.map(item => ({
          id: item.nickname, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }
    },
    methods: {
      goinorder() {
        this.$store.dispatch('tagsView/delView', this.$route);
        this.$router.push({
          path: '/saleorder/saleorderadd?oid=' + this.id,
        });
      },
      vdelcart() {
        console.log("vdelcartvdelcart")
        this.formData.certificates = ""
        this.$forceUpdate()
      },
      vgetUploadHandler() {
        return (options) => {
          this.uploadHandlev(options);
        };
      },
      async uploadHandlev(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.certificates = data.url
              this.$forceUpdate()
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },
      onCloseDialog() {
        this.caigou1 = false;
        this.caigou2 = false;
        this.caigou3 = false;
      },
      prints(index) {
        if (index == 1) {
          this.caigou1 = true;
        }
        if (index == 2) {
          this.caigou2 = true;
        }
        if (index == 3) {
          this.caigou3 = true;
        }
        this.printform = this.formData;
        console.log(this.printform)
      },
      handleRowClick(row) {
        this.selectadd(row);
      },
      handleRowMouseEnter(v) {
        this.hoveredIndex = v;
      },
      handleRowMouseLeave() {
        this.hoveredIndex = null; // 鼠标离开时重置悬停索引
      },
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;
            try {
              customerindex(1, 100, {
                name: query
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      remoteidMethod(query) {
        if (query !== '') {
          this.loading = true;
          console.log(query, "dddddddddddddddddddddddd")
          setTimeout(() => {
            this.loading = false;

            try {
              customerindex(1, 100, {
                customerid: query,
              }).then(res => {
                this.customers = res.data
              });
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } catch (error) {
              console.error('Failed to fetch customer:', error);
            }
          }, 200);
        } else {
          this.customers = [];
        }
      },
      oncopyproductname(row, index) {
        this.xiabiao = this.xiabiao + 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: row.productname + "01",
          sku: row.sku,
          csku: row.csku,
          uom: row.uom,
          cskuom: row.cskuom,
          unitweight: row.unitweight,
          unitprice: row.unitprice,
          leadtime: row.leadtime,
          minimumorder: row.minimumorder,
          note: row.note,
          product_id: row.product_id
        });
      },
      changeqt(value) {
        const selectedTerm = this.quotationdescriptions.find(item => item.id === value);
        if (selectedTerm) {
          try {
            this.formData.currency = selectedTerm.currency
            this.formData.quotationdescriptions = [selectedTerm.description]
            this.formData.rate = selectedTerm.rate
            this.$nextTick(() => {
              this.$forceUpdate()
            })
          } catch (error) {
            console.error('Failed to fetch customer:', error);
            this.$set(this.formData, 'currency', '')
            this.$set(this.formData, 'quotationdescriptions', [])
            this.$set(this.formData, 'rate', '')
          }
        }
      },
      async changetermc(value) {
        const selectedTerm = this.customers.find(item => item.id === value);
        if (selectedTerm) {
          try {
            var {
              data
            } = await billingindex(1, 100, {
              customer_id: value
            });
            this.billingtitle = data
            if (this.billingtitle.length > 0) {
              this.formData.billingtitle = this.billingtitle[0].title
              this.formData.attention = this.billingtitle[0].attention
              this.formData.fax = this.billingtitle[0].fax
              this.formData.tel = this.billingtitle[0].tel
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            } else {
              this.$set(this.formData, 'billingtitle', '')
              this.$set(this.formData, 'attention', '')
              this.$set(this.formData, 'fax', '')
              this.$set(this.formData, 'tel', '')
            }
          } catch (error) {
            console.error('Failed to fetch customer:', error);
            this.$set(this.formData, 'billingtitle', '')
            this.$set(this.formData, 'attention', '')
            this.$set(this.formData, 'fax', '')
            this.$set(this.formData, 'tel', '')
          }
        }
      },
      changebt(value) {
        const selectedbt = this.billingtitle.find(item => item.title === value);
        if (selectedbt) {
          this.formData.billingtitle = selectedbt.title
          this.formData.attention = selectedbt.attention
          this.formData.fax = selectedbt.fax
          this.formData.tel = selectedbt.tel
        }
        this.$forceUpdate()
      },
      changeterm(value) {
        const selectedTerm = this.term.find(item => item.name === value);
        if (selectedTerm) {
          this.formData.termdata = selectedTerm.shipmentterm
          this.formData.termdataday = selectedTerm.shipmenttermday
        }
      },
      showButton(index) {
        if (isdiable || isapproved) {
          return
        }
        this.hoveredIndex = index; // 设置当前鼠标悬停的行的索引
      },
      hideButton(index) {
        if (isdiable) {
          return
        }
        if (this.hoveredIndex === index) {
          this.hoveredIndex = null; // 清除当前鼠标悬停的行的索引
        }
        // 注意：这里其实不需要传入 index，因为 mouseleave 事件已经足够判断鼠标离开了当前元素
        // 但为了保持与 showButton 方法参数的一致性，这里还是传入了 index（尽管未使用）
      },
      delcart(index) {
        this.formData.procureditem[index].certificates = null
      },
      getUploadHandler(index) {
        // 返回一个函数，该函数将作为 http-request 的处理器
        return (options) => {
          // 在这里，我们可以安全地使用 index，因为它是在这个闭包中捕获的
          this.rowIndex = index; // 如果需要在 uploadHandle 中使用，可以临时存储到组件的 data 或 properties 中
          this.uploadHandle(options);
        };
      },
      async uploadHandle(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.procureditem[this.rowIndex].certificates = data.url
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },
      godisable() {
        this.isdiable = !this.isdiable
      },
      addItem() { //增加行
        this.xiabiao += 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: "",
          csku: "",
          sku: "",
          uom: "",
          cskuom: "",
          unitweight: "",
          unitprice: "",
          leadtime: "",
          minimumorder: "",
          note: "",
          product_id: ""
        });
      },
      removeItem(row) {
        const index = this.formData.procureditem.indexOf(row)
        if (this.formData.procureditem.length > 1) {
          this.formData.procureditem.splice(index, 1);
        } else {
          this.$message.error("Keep at least one row of data!")
        }
      },
      async editstatus(id, statusdata) {
        console.log(id)
        try {
          await this.$confirm("This operation will permanently Save status. Do you want to continue?", "prompt", {
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
            type: "warning"
          });
          let {
            info
          } = await update({
            id: id,
            action: "status",
            status: statusdata
          });
          this.$message.success("Status update successful");
          this.isapproved = true

          // 刷新当前页
          const {
            data
          } = await show(this.id);
          this.formData = data;
          if (this.formData.status == "approved") {
            this.isapproved = true
          }
          if (this.formData.status == "rejection") {
            this.isapproved = false
            this.isdiable = true
            this.formData.status == "rejection"
          }
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled save"
          });
        }
      },
      selectadd(row) {
        if (row) {
          // skushow(1, 1, {
          //   product_id: row.id
          // }).then(res => {
          //   if (res.data) {
          //     this.formData.procureditem[this.tindex].suppliesku = res.data[0].csku
          //     // this.formData.procureditem[this.tindex].costprice = res.data[0].price
          //   }
          // });

          this.formData.procureditem[this.tindex].productname = row.name
          this.formData.procureditem[this.tindex].csku = row.csku
          this.formData.procureditem[this.tindex].sku = row.sku
          this.formData.procureditem[this.tindex].unitprice = row.price
          this.formData.procureditem[this.tindex].product_id = row.id
          this.formData.procureditem[this.tindex].uom = row.uom
          this.formData.procureditem[this.tindex].cskuom = row.cskuom

          console.log(this.formData.procureditem)
          this.isgoprolist = false;
        }
      },
      onChangeproductname(proname, index, event) {
        this.$nextTick(() => {
          this.topx = this.x + "px";
          console.log('Input coordinates:', this.x, this.y);
        });
        if (proname) {
          this.tindex = index
          prolist(1, 100, {
            name: proname
          }).then(res => {
            this.tableData = res.data
            this.isgoprolist = true;
          });
        }
      },
      onChangeproductsku(sku, index, event) {
        console.log(index)
        this.$nextTick(() => {
          this.topx = this.x + "px";
          console.log('Input coordinates:', this.x, this.y);
        });
        if (sku) {
          if (this.formData.staff) {
            warehouselist(1, 1, {
              belongingsales: this.formData.staff,
            }).then(res => {
              if (res.data) {
                this.tindex = index
                prolist(1, 100, {
                  sku: sku,
                  warehouse_id: res.data[0].id
                }).then(res => {
                  this.tableData = res.data
                  this.isgoprolist = true;
                });
              }
            });
          }
        }
      },
      checkDataAndGetPosition(inputElement) {
        if (inputElement.value === '') {
          setTimeout(() => {
            this.checkDataAndGetPosition(inputElement);
          }, 1000); // 等待1秒后再次尝试获取数据
        } else {
          const inputRect = inputElement.getBoundingClientRect();
          const inputCoordinates = {
            x: inputRect.left,
            y: inputRect.top
          };
          console.log('Input coordinates:', inputCoordinates);
        }
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      edit(id) {
        this.$router.push({
          path: '/product/editproduct',
          query: {
            id: id
          }
        })
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.save(form);
      },
      close() {
        this.$router.push({
          path: '/salemodel/quotationlist'
        });
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.isubmit = true
              for (var i = 0; i < this.formData.procureditem.length; i++) {
                var tm = this.formData.procureditem[i].productname
                if (tm == "") {
                  this.$message.error("Please add a product data");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].sku
                if (tm == "") {
                  this.$message.error("Please add a product sku");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].unitweight
                if (tm == "") {
                  this.$message.error("Please add a product unitweight");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].unitprice
                if (tm == "") {
                  this.$message.error("Please add a product unitprice");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].minimumorder
                if (tm == "") {
                  this.$message.error("Please add a product minimumorder");
                  this.isubmit = false
                  return false
                }
              }

              this.formData.items = this.formData.procureditem.length
              for (var i = 0; i < this.customers.length; i++) {
                this.formData.customername = this.customers[i].name
              }

              this.formData.quotationdescriptions = this.formData.quotationdescriptions.toString()

              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/salemodel/quotationlist'
                  });
                }, 1000);
              }
              if (this.isNew) {
                if (this.formData.procureditem != null && this.formData.procureditem.length > 0) {

                } else {
                  this.$message.error("Please add a product");
                  return false
                }
                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                if (info1) {
                  if (info1.status_code = 201) {
                    this.$message.success("Add successfully");
                    setTimeout(() => {
                      this.$store.dispatch('tagsView/delView', this.$route);
                      this.$router.push({
                        path: '/quotationlist/editquotationlist',
                        query: {
                          id: info1.info
                        }
                      })
                    }, 1000);
                  } else {
                    this.isubmit = false
                    this.$message.error(
                      "Data verification error");
                    return false;
                  }
                }
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.isubmit = false
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.isubmit = false
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              //this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        console.log("sssssssssssssssssss")
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
          console.log(reader.result)
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }

    }
  }
</script>
<style>
  .avatar-uploader {
    position: relative;
  }

  .ordernumber {
    margin-top: 30px;
    border: 0px;
    text-align: center;
    position: relative;
    left: 85%;
    display: inline-block;
    top: 28px;
    font-size: 16px;
    height: 30px;
    line-height: 30px;
    width: 100px;
  }

  .bba .el-dialog__body {
    padding: 30px 20px !important;
    color: #606266;
  }

  .customWidth {
    width: 80%;
  }

  .tableDatav .has-gutter {
    display: none;
  }

  .cadd {
    width: 100%;
  }

  .plt {
    position: absolute;
    z-index: 9999;
    left: 170px;
    background-color: #f5f5f5;
  }

  #cadd .el-table th.el-table__cell>.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    font-weight: 600 !important;
    color: #000;
    font-size: 14px !important;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .el-dialog__body {
    padding: 0;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>